package com.fnzx.util.common;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.fnzx.entity.CooperativeUserEntity;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author: Wang Zhifu
 * @create: 2021/11/19 15:06
 * @Description:
 */
public class ExcelUtil<T> {
    public void export(String fileName, List<T> dataList, HttpServletResponse response){
        try {
            //获取需要导出的数据
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            //内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyExcel没有关系
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), dataList.get(0).getClass())
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .sheet(fileName)
                    .doWrite(dataList);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
